<template>
  <div class="game-result-page">
    <!-- 背景特效 -->
    <div class="background-effects">
      <div class="particle" v-for="n in 20" :key="n" :style="getParticleStyle(n)"></div>
    </div>

    <div class="result-container">
      <!-- 胜负结果展示 -->
      <section class="result-header">
        <div class="result-crown" v-if="isWinner">👑</div>
        <h1 class="result-title" :class="resultClass">
          {{ resultTitle }}
        </h1>
        <p class="result-subtitle">{{ resultSubtitle }}</p>
      </section>

      <!-- 最终排名展示 -->
      <section class="ranking-section">
        <h2>🏆 最终排名</h2>
        <div class="podium">
          <!-- 前三名颁奖台 -->
          <div
            v-for="(player, index) in topThreePlayers"
            :key="player.id"
            class="podium-position"
            :class="`position-${index + 1}`"
          >
            <div class="podium-player">
              <div class="player-avatar">{{ player.avatar }}</div>
              <div class="player-name">{{ player.name }}</div>
              <div class="player-area">{{ player.area }}%</div>
            </div>
            <div class="podium-base">
              <div class="position-number">{{ index + 1 }}</div>
              <div class="position-score">+{{ player.rankScore }}分</div>
            </div>
          </div>
        </div>

        <!-- 完整排名列表 -->
        <div class="full-ranking">
          <div
            v-for="(player, index) in finalRanking"
            :key="player.id"
            class="rank-item"
            :class="{
              'is-current': player.id === currentUserId,
              'is-winner': index === 0,
              'is-last': index === finalRanking.length - 1
            }"
          >
            <div class="rank-position">
              <span class="rank-number">{{ index + 1 }}</span>
              <span class="rank-medal" v-if="index < 3">{{ getRankMedal(index) }}</span>
            </div>
            <div class="player-color" :style="{ backgroundColor: player.color }"></div>
            <div class="player-info">
              <div class="player-name">{{ player.name }}</div>
              <div class="player-stats">
                <span class="area-stat">面积: {{ player.area }}%</span>
                <span class="score-stat">得分: {{ player.totalScore }}</span>
              </div>
            </div>
            <div class="rank-reward">
              <span class="score-change" :class="player.rankScore >= 0 ? 'positive' : 'negative'">
                {{ player.rankScore >= 0 ? '+' : '' }}{{ player.rankScore }}
              </span>
            </div>
          </div>
        </div>
      </section>

      <!-- 个人详细统计 -->
      <section class="personal-stats">
        <h2>📊 个人统计</h2>
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon">🎯</div>
            <div class="stat-content">
              <div class="stat-value">{{ personalStats.finalArea }}%</div>
              <div class="stat-label">最终占领面积</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">🎨</div>
            <div class="stat-content">
              <div class="stat-value">{{ personalStats.paintedCells }}</div>
              <div class="stat-label">涂色格数</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">⚡</div>
            <div class="stat-content">
              <div class="stat-value">{{ personalStats.maxCombo }}</div>
              <div class="stat-label">最高连击</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">⏱️</div>
            <div class="stat-content">
              <div class="stat-value">{{ formatTime(personalStats.survivalTime) }}</div>
              <div class="stat-label">存活时间</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">🔥</div>
            <div class="stat-content">
              <div class="stat-value">{{ personalStats.territoryTaken }}</div>
              <div class="stat-label">抢夺地盘次数</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">🛡️</div>
            <div class="stat-content">
              <div class="stat-value">{{ personalStats.territoryLost }}</div>
              <div class="stat-label">失去地盘次数</div>
            </div>
          </div>
        </div>
      </section>

      <!-- 游戏回放控制 -->
      <section class="replay-section">
        <h2>🎬 游戏回放</h2>
        <!-- 重新设计布局：水平排列 -->
        <div class="replay-controls">
          <!-- 左侧：播放控制按钮 -->
          <div class="playback-buttons">
            <button @click="playReplay" class="btn btn-primary" :disabled="isReplayPlaying">
              <span class="btn-icon">▶️</span>
              <span class="btn-text">播放</span>
            </button>
            <button @click="pauseReplay" class="btn btn-secondary" :disabled="!isReplayPlaying">
              <span class="btn-icon">⏸️</span>
              <span class="btn-text">暂停</span>
            </button>
            <button @click="restartReplay" class="btn btn-secondary">
              <span class="btn-icon">🔄</span>
              <span class="btn-text">重播</span>
            </button>
          </div>
          
          <!-- 中间：进度条区域 -->
          <div class="progress-section">
            <div class="progress-info">
              <span class="progress-label">回放进度</span>
              <span class="progress-time">{{ formatTime(replayTime / 1000) }}</span>
            </div>
            
            <div class="progress-bar-container">
            <input
              v-model="replayProgress"
              type="range"
              min="0"
              max="100"
                step="0.1"
                class="progress-slider"
                @input="handleProgressChange"
                @mousedown="onProgressDragStart"
                @mouseup="onProgressDragEnd"
                @touchstart="onProgressDragStart"
                @touchend="onProgressDragEnd"
              />
              <div class="progress-fill" :style="{ width: replayProgress + '%' }"></div>
              <div class="progress-thumb" :style="{ left: replayProgress + '%' }"></div>
            </div>
            
            <div class="progress-labels">
              <span>开始</span>
              <span>{{ formatTime(gameResult.duration) }}</span>
            </div>
          </div>
          
          <!-- 右侧：录制控制按钮 -->
          <div class="recording-buttons">
            <div class="recording-controls">
              <button 
                @click="startRecordingOnClick" 
                class="btn btn-danger" 
                :disabled="isRecording"
                title="从当前进度开始录制游戏画面"
              >
                <span class="btn-icon">{{ isRecording ? '●' : '' }}</span>
                <span class="btn-text">{{ isRecording ? '录制中' : '录制' }}</span>
            </button>
              
              <button 
                @click="stopRecording" 
                class="btn btn-secondary" 
                :disabled="!isRecording"
              >
                <span class="btn-icon">⏹️</span>
                <span class="btn-text">停止</span>
            </button>
              
              <button 
                @click="downloadRecording" 
                class="btn btn-success" 
                :disabled="recordedChunks.length === 0"
              >
                <span class="btn-icon"></span>
                <span class="btn-text">下载</span>
              </button>
              
              <button 
                @click="clearRecording" 
                class="btn btn-secondary" 
                :disabled="recordedChunks.length === 0"
              >
                <span class="btn-icon">🗑️</span>
                <span class="btn-text">清除</span>
            </button>
            </div>
          </div>
        </div>
        <div class="replay-canvas-container">
          <canvas
            ref="replayCanvas"
            class="replay-canvas"
            width="600"
            height="400"
          ></canvas>
          <div class="replay-overlay" v-if="!isReplayPlaying && replayProgress === 0">
            <div class="play-button" @click="toggleReplay">
              <span>▶️</span>
            </div>
          </div>
        </div>
      </section>

      <!-- 操作按钮 -->
      <section class="action-buttons">
        <div class="button-row">
          <button 
            @click="playAgain" 
            class="btn btn-success btn-large"
            :disabled="isProcessing"
          >
            <span class="btn-icon">🔄</span>
            <span class="btn-text">{{ isProcessing ? '处理中...' : '再来一局' }}</span>
            <span class="btn-loading" v-if="isProcessing">⏳</span>
          </button>
          <button @click="backToLobby" class="btn btn-primary btn-large">
            <span class="btn-icon">🏠</span>
            <span class="btn-text">返回大厅</span>
          </button>
        </div>
        
        <!-- 开发环境测试按钮 -->
        <div v-if="isDevelopment" class="test-controls">
          <button @click="addTestData" class="btn btn-secondary">
            🧪 加载测试数据
          </button>
          <button @click="resetTestData" class="btn btn-secondary">
            🔄 重置数据
          </button>
          <button @click="showDebugInfo" class="btn btn-secondary">
            🔍 调试信息
          </button>
          <button @click="testProgressCalculation" class="btn btn-secondary">
            📊 测试进度
          </button>
          <button @click="validateTimeData" class="btn btn-secondary">
            ⏱️ 验证时间
          </button>
        </div>
        
        <div class="button-row">
          <button @click="openShareModal" class="btn btn-secondary">
            <span class="btn-icon">📤</span>
            <span class="btn-text">分享结果</span>
          </button>
          <button @click="saveScreenshot" class="btn btn-secondary">
            <span class="btn-icon">📸</span>
            <span class="btn-text">保存截图</span>
          </button>
          <button @click="viewProfile" class="btn btn-secondary">
            <span class="btn-icon">👤</span>
            <span class="btn-text">查看个人资料</span>
          </button>
        </div>
      </section>
    </div>

    <!-- 分享模态框 -->
    <div v-if="showShareModal" class="share-modal-overlay" @click="closeShareModal">
      <div class="share-modal-content" @click.stop>
        <div class="share-modal-header">
          <h3>分享游戏结果</h3>
          <button @click="closeShareModal" class="share-close-btn">&times;</button>
        </div>
        
        <div class="share-content">
          <div class="share-game-info">
            <div class="game-icon">🎨</div>
            <div class="game-title">涂色抢地盘</div>
            <div class="player-performance">
              <div class="performance-text">我在游戏中获得了第{{ currentPlayerRank }}名！</div>
              <div class="performance-area">占领面积: {{ personalStats.finalArea }}%</div>
            </div>
            <div class="challenge-text">一起来挑战吧！</div>
          </div>
          
          <div class="share-buttons">
            <button @click="shareToWeChat" class="share-btn wechat-btn">
              <span class="share-icon">💬</span>
              <span class="share-text">微信分享</span>
            </button>
            <button @click="shareToWeibo" class="share-btn weibo-btn">
              <span class="share-icon">📱</span>
              <span class="share-text">微博分享</span>
            </button>
            <button @click="copyLink" class="share-btn link-btn">
              <span class="share-icon">🔗</span>
              <span class="share-text">复制链接</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Toast提示 -->
    <div v-if="showToast" class="toast-container">
      <div class="toast" :class="`toast-${toastType}`">
        <span class="toast-icon">
          {{ toastType === 'success' ? '✅' : toastType === 'error' ? '❌' : 'ℹ️' }}
        </span>
        <span class="toast-message">{{ toastMessage }}</span>
      </div>
    </div>

    <!-- 录制进度条 -->
    <div v-if="isRecording" class="recording-progress">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: recordingProgress + '%' }"></div>
      </div>
      <p class="progress-text">正在生成回放视频... {{ Math.round(recordingProgress) }}%</p>
    </div>

    <!-- 测试状态显示 -->
    <div v-if="isDevelopment" class="test-status">
      <p>测试模式 - 回放数据: {{ replayData.length }} 步</p>
      <p>当前步骤: {{ currentReplayStep }} / {{ replayData.length - 1 }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { gameResultAPI } from '@/api/gameResult.js'
import wechatShareService from '@/services/wechatShare.js'

const router = useRouter()
const route = useRoute()
const replayCanvas = ref(null)

// 环境变量
const isDevelopment = computed(() => import.meta.env.NODE_ENV === 'development')

// 当前用户ID - 从localStorage或token中获取
const currentUserId = ref('')

// 游戏结果数据 - 从后端API获取
const gameResult = reactive({
  gameId: route.params.id,
  duration: 0,
  winner: null,
  totalPlayers: 0,
  roomId: null,
  endTime: null,
  endReason: null
})

// 最终排名 - 从后端API获取
const finalRanking = ref([])

// 个人统计数据 - 从后端API获取
const personalStats = reactive({
  finalArea: 0,
  paintedCells: 0,
  maxCombo: 0,
  survivalTime: 0,
  territoryTaken: 0,
  territoryLost: 0
})

// 游戏回放数据 - 纯前端生成
const gameReplay = reactive({
  duration: 0,
  isAvailable: true,
  canvasWidth: 600, // 从1200调整为600
  canvasHeight: 400, // 从800调整为400
  gridSize: 25, // 从50调整为25，保持网格密度
  replaySpeed: 1
})

// 回放控制状态
const replayProgress = ref(0)
const isReplayPlaying = ref(false)
const showShareModal = ref(false)
const replayInterval = ref(null)
const currentReplayStep = ref(0)

// 视频录制相关
const mediaRecorder = ref(null)
const recordedChunks = ref([])
const isRecording = ref(false)
const recordingProgress = ref(0)

// 按钮状态
const isProcessing = ref(false)
const showToast = ref(false)
const toastMessage = ref('')
const toastType = ref('success')

// 回放相关变量
const replayTime = ref(0)
const replayData = ref([])

// 当前游戏状态
const currentGameState = reactive({
  grid: Array(20).fill().map(() => Array(15).fill(null)),
  players: []
})

// 加载状态
const isLoading = ref(true)
const loadError = ref(null)

// 计算属性
const currentPlayerRank = computed(() => {
  const player = finalRanking.value.find(p => p.id === currentUserId.value)
  return player ? finalRanking.value.indexOf(player) + 1 : 0
})

const isWinner = computed(() => {
  return currentPlayerRank.value === 1
})

const resultClass = computed(() => {
  if (isWinner.value) return 'winner'
  if (currentPlayerRank.value <= 3) return 'good'
  return 'normal'
})

const resultTitle = computed(() => {
  const rank = currentPlayerRank.value
  if (rank === 1) return '🎉 恭喜获胜！'
  if (rank === 2) return '🥈 获得亚军！'
  if (rank === 3) return '🥉 获得季军！'
  return '游戏结束'
})

const resultSubtitle = computed(() => {
  const rank = currentPlayerRank.value
  if (rank === 1) return '你是本局游戏的王者！'
  if (rank <= 3) return '表现优秀，继续加油！'
  return '虽败犹荣，下次一定能赢！'
})

const topThreePlayers = computed(() => {
  return finalRanking.value.slice(0, 3)
})

// 工具方法
const getRankMedal = (index) => {
  const medals = ['🥇', '🥈', '🥉']
  return medals[index] || ''
}

const getParticleStyle = (n) => {
  return {
    left: `${Math.random() * 100}%`,
    animationDelay: `${Math.random() * 3}s`,
    animationDuration: `${3 + Math.random() * 4}s`
  }
}

const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// API调用方法 - 根据后端接口调整
const loadGameResult = async () => {
  try {
    isLoading.value = true
    loadError.value = null
    
    console.log('开始加载游戏结果，游戏ID:', gameResult.gameId)
    
    // 调用后端 /api/game/{gameId}/result 接口
    const resultResponse = await gameResultAPI.getGameResult(gameResult.gameId)
    console.log('游戏结果API响应:', resultResponse)
    
    if (resultResponse.success) {
      const resultData = resultResponse.data
      
      // 根据后端返回的数据结构更新游戏结果
      Object.assign(gameResult, {
        duration: resultData.duration || 0,
        winner: resultData.winner,
        totalPlayers: resultData.statistics?.totalPlayers || 0,
        endTime: resultData.endTime,
        endReason: resultData.statistics?.endReason
      })
      
      // 更新排名数据 - 使用后端返回的 rankings 数组
      if (resultData.rankings) {
        finalRanking.value = resultData.rankings.map((player, index) => ({
          id: player.playerId,
          name: player.playerName,
          avatar: getPlayerAvatar(player.playerName),
          color: getPlayerColor(index),
          area: player.territoryPercentage || 0,
          totalScore: player.score || 0,
          rankScore: calculateRankScore(index + 1, player.score || 0)
        }))
      }
      
      // 获取当前用户ID（从获胜者或排名中推断）
      if (resultData.winner) {
        currentUserId.value = resultData.winner.playerId
      } else if (finalRanking.value.length > 0) {
        // 暂时使用第一个玩家作为当前用户（实际应该从认证信息获取）
        currentUserId.value = finalRanking.value[0].id
      }
      
      // 获取个人统计数据
      await loadPersonalStats()
      
      console.log('游戏结果加载完成:', {
        gameResult,
        finalRanking: finalRanking.value,
        currentUserId: currentUserId.value
      })
    } else {
      throw new Error(resultResponse.message || '获取游戏结果失败')
    }
    
  } catch (error) {
    console.error('加载游戏结果失败:', error)
    loadError.value = error.message || '加载游戏结果失败'
    showToastMessage('加载游戏结果失败，请重试', 'error')
    
    // 如果API调用失败，使用默认测试数据
    useDefaultTestData()
  } finally {
    isLoading.value = false
  }
}

const loadPersonalStats = async () => {
  try {
    if (!currentUserId.value) return
    
    // 调用后端 /api/game/{gameId}/player/{playerId} 接口
    const playerResponse = await gameResultAPI.getPlayerState(gameResult.gameId, currentUserId.value)
    console.log('玩家状态API响应:', playerResponse)
    
    if (playerResponse.success) {
      const playerData = playerResponse.data
      
      // 根据后端返回的数据结构更新个人统计数据
      Object.assign(personalStats, {
        finalArea: playerData.totalTerritoryArea || 0,
        paintedCells: playerData.statistics?.territoryCaptures || 0,
        maxCombo: playerData.statistics?.kills || 0,
        survivalTime: gameResult.duration,
        territoryTaken: playerData.statistics?.territoryCaptures || 0,
        territoryLost: playerData.statistics?.deaths || 0
      })
      
      console.log('个人统计数据加载完成:', personalStats)
    }
  } catch (error) {
    console.error('加载个人统计数据失败:', error)
    // 使用默认数据
    useDefaultPersonalStats()
  }
}

const loadGameRanking = async () => {
  try {
    // 调用后端 /api/game/{gameId}/ranking 接口
    const rankingResponse = await gameResultAPI.getGameRanking(gameResult.gameId)
    console.log('游戏排名API响应:', rankingResponse)
    
    if (rankingResponse.success && rankingResponse.data) {
      finalRanking.value = rankingResponse.data.map((player, index) => ({
        id: player.playerId,
        name: player.playerName,
        avatar: getPlayerAvatar(player.playerName),
        color: getPlayerColor(index),
        area: player.areaPercentage || 0,
        totalScore: player.territoryArea || 0,
        rankScore: calculateRankScore(index + 1, player.territoryArea || 0)
      }))
    }
  } catch (error) {
    console.error('加载游戏排名失败:', error)
    // 使用默认排名数据
    useDefaultRankingData()
  }
}

// 默认数据方法 - 当API调用失败时使用
const useDefaultTestData = () => {
  console.log('使用默认测试数据')
  
  // 设置默认游戏结果
  Object.assign(gameResult, {
    duration: 300,
    winner: 'player-3',
    totalPlayers: 4,
    roomId: null,
    endTime: new Date(),
    endReason: 'TimeExpired'
  })
  
  // 设置默认排名
  finalRanking.value = [
    {
      id: 'player-3',
      name: '玩家3',
      avatar: '🤖',
      color: '#45b7d1',
      area: 28.7,
      totalScore: 1420,
      rankScore: 6
    },
    {
      id: 'player-1',
      name: '我自己',
      avatar: '😀',
      color: '#ff6b6b',
      area: 25.5,
      totalScore: 1250,
      rankScore: 4
    },
    {
      id: 'player-4',
      name: '玩家4',
      avatar: '⚡',
      color: '#f7b731',
      area: 23.5,
      totalScore: 1180,
      rankScore: 2
    },
    {
      id: 'player-2',
      name: '玩家2',
      avatar: '',
      color: '#4ecdc4',
      area: 22.3,
      totalScore: 1100,
      rankScore: -1
    }
  ]
  
  currentUserId.value = 'player-1'
  useDefaultPersonalStats()
}

const useDefaultPersonalStats = () => {
  Object.assign(personalStats, {
    finalArea: finalRanking.value.find(p => p.id === currentUserId.value)?.area || 25.5,
    paintedCells: 324,
    maxCombo: 15,
    survivalTime: gameResult.duration,
    territoryTaken: 12,
    territoryLost: 8
  })
}

const useDefaultRankingData = () => {
  // 如果排名API失败，使用默认排名
  if (finalRanking.value.length === 0) {
    useDefaultTestData()
  }
}

// 辅助方法
const getPlayerAvatar = (playerName) => {
  const avatars = ['', '', '🤖', '⚡', '🎮', '🏆']
  const index = playerName.length % avatars.length
  return avatars[index]
}

const getPlayerColor = (index) => {
  const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#f7b731', '#96ceb4', '#ff9ff3']
  return colors[index % colors.length]
}

const calculateRankScore = (rank, score) => {
  // 根据排名和分数计算得分变化
  const baseScore = score / 100
  switch (rank) {
    case 1: return Math.round(baseScore * 6)
    case 2: return Math.round(baseScore * 4)
    case 3: return Math.round(baseScore * 2)
    default: return Math.round(baseScore * 1)
  }
}

// 按钮功能方法
const playAgain = async () => {
  try {
    isProcessing.value = true
    
    if (gameResult.roomId) {
      router.push(`/room/${gameResult.roomId}`)
      return
    }
    
    router.push('/lobby')
    
  } catch (error) {
    console.error('再来一局失败:', error)
    showToastMessage('再来一局失败，请重试', 'error')
  } finally {
    isProcessing.value = false
  }
}

const backToLobby = () => {
  try {
    router.push('/lobby')
  } catch (error) {
    console.error('返回大厅失败:', error)
    showToastMessage('返回大厅失败，请重试', 'error')
  }
}

// 分享相关方法
const openShareModal = () => {
  showShareModal.value = true
  console.log('打开分享模态框')
}

const closeShareModal = () => {
  showShareModal.value = false
}

// 改进Toast提示函数，支持自动消失
const showToastMessage = (message, type = 'info') => {
  console.log(`Toast [${type}]: ${message}`)
  
  // 创建Toast元素
  const toast = document.createElement('div')
  toast.className = `toast toast-${type}`
  toast.innerHTML = `
    <span class="toast-icon">
      ${type === 'success' ? '✅' : type === 'error' ? '❌' : 'ℹ️'}
    </span>
    <span class="toast-message">${message}</span>
  `
  
  // 添加Toast样式
  const style = document.createElement('style')
  style.textContent = `
    .toast {
      position: fixed;
      top: 20px;
      right: 20px;
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 1rem 1.5rem;
      border-radius: 8px;
      color: #fff;
      font-weight: 600;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      animation: slideIn 0.3s ease;
      z-index: 10000;
      max-width: 300px;
    }
    .toast-success {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
    .toast-error {
      background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
    }
    .toast-info {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    @keyframes slideIn {
      from {
        transform: translateX(100%);
        opacity: 0;
      }
      to {
        transform: translateX(0);
        opacity: 1;
      }
    }
    @keyframes slideOut {
      from {
        transform: translateX(0);
        opacity: 1;
      }
      to {
        transform: translateX(100%);
        opacity: 0;
      }
    }
  `
  
  document.head.appendChild(style)
  document.body.appendChild(toast)
  
  // 根据消息类型设置不同的显示时间
  const duration = type === 'error' ? 5000 : type === 'success' ? 3000 : 2000
  
  // 自动消失
  setTimeout(() => {
    toast.style.animation = 'slideOut 0.3s ease'
    setTimeout(() => {
      toast.remove()
      style.remove()
    }, 300)
  }, duration)
}

// 添加缺失的testWechatShare函数
const testWechatShare = () => {
  console.log('测试微信分享服务...')
  console.log('wechatShareService 类型:', typeof wechatShareService)
  console.log('wechatShareService 方法:', Object.keys(wechatShareService))
  
  if (wechatShareService && typeof wechatShareService.shareToWechat === 'function') {
    console.log('wechatShareService.shareToWechat 可用')
  } else {
    console.error('wechatShareService.shareToWechat 不可用')
  }
}

// 修复微信分享方法
const shareToWeChat = async () => {
  try {
    console.log('开始微信分享...')
    console.log('wechatShareService:', wechatShareService)
    
    const shareData = {
      title: `我在涂色抢地盘游戏中获得了第${currentPlayerRank.value}名！`,
      desc: `占领面积: ${personalStats.finalArea}%，一起来挑战吧！`,
      link: window.location.href
    }
    
    console.log('分享数据:', shareData)
    
    // 检查wechatShareService是否可用
    if (!wechatShareService) {
      console.error('wechatShareService 未正确导入')
      showToastMessage('微信分享服务未加载', 'error')
      return
    }
    
    // 使用wechatShareService
    console.log('调用 wechatShareService.shareToWechat...')
    const result = await wechatShareService.shareToWechat(shareData)
    
    console.log('分享结果:', result)
    
    if (result && result.success) {
      showToastMessage(result.message, 'success')
    } else {
      showToastMessage(result?.message || '分享失败', 'error')
    }
    
    closeShareModal()
  } catch (error) {
    console.error('微信分享失败:', error)
    console.error('错误详情:', error.message)
    showToastMessage(`分享失败: ${error.message}`, 'error')
  }
}

// 修复微博分享方法
const shareToWeibo = async () => {
  try {
    const text = `我在涂色抢地盘游戏中获得了第${currentPlayerRank.value}名！占领面积: ${personalStats.finalArea}%，一起来挑战吧！`
    const url = window.location.href
    
    // 使用微博官方分享弹窗
    const weiboUrl = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(url)}&title=${encodeURIComponent(text)}&appkey=YOUR_APP_KEY&pic=${encodeURIComponent('/game-share-image.png')}`
    
    // 打开微博分享弹窗
    const popup = window.open(
      weiboUrl,
      'weibo_share',
      'width=600,height=400,scrollbars=yes,resizable=yes,status=yes,location=yes,toolbar=no,menubar=no'
    )
    
    // 检查弹窗是否被阻止
    if (!popup || popup.closed || typeof popup.closed === 'undefined') {
      // 如果弹窗被阻止，显示提示
      showToastMessage('弹窗被阻止，请允许弹窗后重试', 'error')
      
      // 提供备选方案
      if (confirm('弹窗被阻止，是否直接跳转到微博？')) {
        window.open(weiboUrl, '_blank')
      }
    } else {
      showToastMessage('微博分享弹窗已打开', 'success')
    }
    
    closeShareModal()
  } catch (error) {
    console.error('微博分享失败:', error)
    showToastMessage('分享失败，请重试', 'error')
  }
}

// 修复复制链接方法
const copyLink = async () => {
  try {
    const shareText = `我在涂色抢地盘游戏中获得了第${currentPlayerRank.value}名！占领面积: ${personalStats.finalArea}%，一起来挑战吧！\n${window.location.href}`
  
    if (navigator.clipboard) {
      await navigator.clipboard.writeText(shareText)
    } else {
      // 降级处理
      const textArea = document.createElement('textarea')
      textArea.value = shareText
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
    }
    
    showToastMessage('链接已复制到剪贴板', 'success')
    closeShareModal()
  } catch (error) {
    console.error('复制失败:', error)
    showToastMessage('复制失败，请重试', 'error')
  }
}

// 在组件挂载时测试
onMounted(async () => {
  console.log('GameResultPage 组件挂载，游戏ID:', gameResult.gameId)
  
  try {
    // 加载游戏结果数据
    await loadGameResult()
    
    // 如果游戏结果加载失败，尝试加载排名数据
    if (finalRanking.value.length === 0) {
      await loadGameRanking()
    }
    
    // 初始化回放数据 - 优先使用真实数据，降级到模拟数据
    replayData.value = loadRealReplayData()
    
    // 初始化画布
    nextTick(() => {
      drawReplayCanvas()
    })
    
    // 测试微信分享服务
    testWechatShare()
    
  } catch (error) {
    console.error('页面初始化失败:', error)
    handleApiError(error, '页面初始化')
  }
})

onUnmounted(() => {
  // 清理资源
  if (replayInterval.value) {
    clearInterval(replayInterval.value)
  }
})

// 保留你所有的回放相关方法 - 这些方法保持不变
// 回放控制方法
const toggleReplay = () => {
  console.log('切换回放状态:', !isReplayPlaying.value)
  isReplayPlaying.value = !isReplayPlaying.value
  
  if (isReplayPlaying.value) {
    playReplay()
  } else {
    pauseReplay()
  }
}

// 修复回放播放方法
const playReplay = () => {
  console.log('开始播放回放...')
  
  if (replayData.value.length === 0) {
    console.log('没有回放数据，生成测试数据')
    replayData.value = generateTestData()
  }
  
  if (replayData.value.length === 0) {
    console.log('生成测试数据失败')
      return
    }
    
  console.log('回放数据长度:', replayData.value.length)
  console.log('从步骤开始播放:', currentReplayStep.value)
  
  // 检查是否已经播放完成
  if (currentReplayStep.value >= replayData.value.length - 1) {
    currentReplayStep.value = 0
    replayProgress.value = 0
    replayTime.value = 0
  }
  
  isReplayPlaying.value = true
  console.log('开始回放播放...')
  startReplayPlayback()
}

const startReplayPlayback = () => {
  if (replayInterval.value) {
    clearInterval(replayInterval.value)
  }
  
  // 执行初始步骤
  const initialStepData = replayData.value[currentReplayStep.value]
  if (initialStepData) {
    executeReplayStep(initialStepData)
    if (initialStepData.timestamp !== undefined) {
      replayTime.value = initialStepData.timestamp
    }
  }
  
  replayInterval.value = setInterval(() => {
    if (currentReplayStep.value < replayData.value.length - 1) {
      currentReplayStep.value++
      
      // 修复进度条计算
      const totalSteps = replayData.value.length - 1
      const currentStep = currentReplayStep.value
      const progress = (currentStep / totalSteps) * 100
      replayProgress.value = Math.round(progress)
      
      // 修复时间更新 - 确保正确获取当前步骤的时间
      const stepData = replayData.value[currentReplayStep.value]
      if (stepData && stepData.timestamp !== undefined) {
        replayTime.value = stepData.timestamp
        console.log(`时间更新: ${replayTime.value}ms -> ${formatTime(replayTime.value / 1000)}`)
      }
      
      // 绘制当前步骤
      executeReplayStep(stepData)
      
      // 添加更详细的调试信息
      console.log(`播放步骤 ${currentStep}/${totalSteps}, 进度: ${replayProgress.value}%, 时间: ${formatTime(replayTime.value / 1000)}`)
    } else {
      // 回放结束
      console.log('回放播放完成')
      replayProgress.value = 100
      // 设置最终时间
      const finalStep = replayData.value[replayData.value.length - 1]
      if (finalStep) {
        replayTime.value = finalStep.timestamp
      }
      pauseReplay()
    }
  }, 500) // 每500ms播放一步
}

const pauseReplay = () => {
  console.log('暂停回放')
  isReplayPlaying.value = false
  if (replayInterval.value) {
    clearInterval(replayInterval.value)
    replayInterval.value = null
  }
}

// 添加重播功能
const restartReplay = () => {
  console.log('重新开始回放')
  pauseReplay()
  currentReplayStep.value = 0
  replayProgress.value = 0
  replayTime.value = 0
  
  // 重置画布
  drawReplayCanvas()
  
  // 重新开始播放
  setTimeout(() => {
    playReplay()
  }, 100)
}

// 修复绘制回放步骤函数
const drawReplayStep = (step) => {
  if (!step) return
  
  const canvas = replayCanvas.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  // 清空画布
  ctx.fillStyle = '#2c3e50'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  // 绘制网格
  ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)'
  ctx.lineWidth = 1
  
  const gridSize = 20
  for (let x = 0; x < canvas.width; x += gridSize) {
    ctx.beginPath()
    ctx.moveTo(x, 0)
    ctx.lineTo(x, canvas.height)
    ctx.stroke()
  }
  
  for (let y = 0; y < canvas.height; y += gridSize) {
    ctx.beginPath()
    ctx.moveTo(0, y)
    ctx.lineTo(canvas.width, y)
    ctx.stroke()
  }
  
  // 根据步骤类型绘制
  switch (step.type) {
    case 'init':
      drawInitialState(ctx, step.data)
      break
    case 'move':
      drawPaintStep(ctx, step.data) // 修复：move类型应该调用drawPaintStep
      break
    case 'paint':
      drawPaintStep(ctx, step.data)
      break
    case 'territory':
      drawCurrentState(ctx) // 圈地完成后显示当前状态
      break
    case 'death':
      drawCurrentState(ctx) // 死亡后显示当前状态
      break
    case 'respawn':
      drawPaintStep(ctx, step.data) // 复活后显示玩家位置
      break
    case 'end':
      drawCurrentState(ctx) // 游戏结束时显示最终状态
      break
    default:
      drawCurrentState(ctx)
  }
  
  // 绘制当前步骤信息
  drawStepInfo(ctx, step)
}

// 修复绘制初始状态函数
const drawInitialState = (ctx, data) => {
  console.log('绘制初始状态:', data)
  
  // 清空画布
  ctx.fillStyle = '#2c3e50'
  ctx.fillRect(0, 0, gameReplay.canvasWidth, gameReplay.canvasHeight)
  
  // 绘制网格
  ctx.strokeStyle = 'rgba(255, 255, 255, 0.05)'
  ctx.lineWidth = 1
  
  for (let x = 0; x <= gameReplay.canvasWidth; x += gameReplay.gridSize) {
    ctx.beginPath()
    ctx.moveTo(x, 0)
    ctx.lineTo(x, gameReplay.canvasHeight)
    ctx.stroke()
  }
  
  for (let y = 0; y <= gameReplay.canvasHeight; y += gameReplay.gridSize) {
    ctx.beginPath()
    ctx.moveTo(0, y)
    ctx.lineTo(gameReplay.canvasHeight, y)
    ctx.stroke()
  }
  
  // 绘制出生点
  if (data.players) {
    data.players.forEach((player, index) => {
      const spawnPoint = player.spawnPoint || { x: 50 + index * 150, y: 50 + Math.floor(index / 2) * 100 }
      
      // 绘制出生点安全区域
      ctx.strokeStyle = player.color
      ctx.lineWidth = 2
      ctx.setLineDash([8, 4])
      ctx.beginPath()
      ctx.arc(spawnPoint.x, spawnPoint.y, 25, 0, Math.PI * 2) // 从50调整为25
      ctx.stroke()
      ctx.setLineDash([])
      
      // 绘制玩家小球
    ctx.fillStyle = player.color
      ctx.beginPath()
      ctx.arc(spawnPoint.x, spawnPoint.y, 6, 0, Math.PI * 2) // 从8调整为6
      ctx.fill()
      
      // 绘制玩家名字
      ctx.fillStyle = '#ffffff'
      ctx.font = 'bold 10px Arial' // 从12px调整为10px
      ctx.textAlign = 'center'
      ctx.fillText(player.name, spawnPoint.x, spawnPoint.y - 15) // 从-20调整为-15
    })
  }
}

// 修复绘制移动步骤函数
const drawPaintStep = (ctx, data) => {
  console.log('绘制移动步骤:', data)
  
  // 先绘制背景和网格
  ctx.fillStyle = '#2c3e50'
  ctx.fillRect(0, 0, gameReplay.canvasWidth, gameReplay.canvasHeight)
  
  // 绘制网格
  ctx.strokeStyle = 'rgba(255, 255, 255, 0.05)'
  ctx.lineWidth = 1
  
  for (let x = 0; x <= gameReplay.canvasWidth; x += gameReplay.gridSize) {
    ctx.beginPath()
    ctx.moveTo(x, 0)
    ctx.lineTo(x, gameReplay.canvasHeight)
    ctx.stroke()
  }
  
  for (let y = 0; y <= gameReplay.canvasHeight; y += gameReplay.gridSize) {
    ctx.beginPath()
    ctx.moveTo(0, y)
    ctx.lineTo(y, gameReplay.canvasHeight)
    ctx.stroke()
  }
  
  // 绘制出生点
  const spawnPoints = [
    { x: 50, y: 50, color: '#ff6b6b' },
    { x: 550, y: 50, color: '#4ecdc4' },
    { x: 550, y: 350, color: '#45b7d1' },
    { x: 50, y: 350, color: '#f7b731' }
  ]
  
  spawnPoints.forEach((spawn, index) => {
    // 绘制出生点安全区域边界
    ctx.strokeStyle = spawn.color
    ctx.lineWidth = 2
    ctx.setLineDash([8, 4])
    ctx.beginPath()
    ctx.arc(spawn.x, spawn.y, 25, 0, Math.PI * 2)
    ctx.stroke()
    ctx.setLineDash([])
  })
  
  if (data.x !== undefined && data.y !== undefined && data.color) {
    // 绘制玩家小球
    ctx.fillStyle = data.color
    ctx.beginPath()
    ctx.arc(data.x, data.y, 6, 0, Math.PI * 2)
    ctx.fill()
    
    // 绘制小球边框
    ctx.strokeStyle = '#ffffff'
    ctx.lineWidth = 2
    ctx.beginPath()
    ctx.arc(data.x, data.y, 6, 0, Math.PI * 2)
    ctx.stroke()
    
    // 如果正在画线，绘制轨迹
    if (data.isDrawing) {
      ctx.strokeStyle = data.color
      ctx.lineWidth = 2
      ctx.lineCap = 'round'
      ctx.lineJoin = 'round'
      
      // 这里需要维护路径状态，简化处理
      ctx.beginPath()
      ctx.moveTo(data.x - 8, data.y - 8)
      ctx.lineTo(data.x, data.y)
      ctx.stroke()
    }
  }
}

// 修复绘制当前状态函数
const drawCurrentState = (ctx) => {
  console.log('绘制当前状态')
  
  // 绘制所有玩家的最终领地
  finalRanking.value.forEach((player, index) => {
    const spawnPoint = [
      { x: 50, y: 50 },
      { x: 550, y: 50 },
      { x: 550, y: 350 },
      { x: 50, y: 350 }
    ][index] || { x: 300, y: 200 }
    
    // 绘制领地（简化版本）
    ctx.fillStyle = player.color + '40' // 半透明
    ctx.beginPath()
    ctx.arc(spawnPoint.x, spawnPoint.y, player.area * 1.5, 0, Math.PI * 2) // 从*3调整为*1.5
    ctx.fill()
    
    // 绘制玩家小球
    ctx.fillStyle = player.color
    ctx.beginPath()
    ctx.arc(spawnPoint.x, spawnPoint.y, 6, 0, Math.PI * 2) // 从8调整为6
    ctx.fill()
  })
}

// 修复绘制步骤信息函数
const drawStepInfo = (ctx, step) => {
  // 绘制步骤信息背景
  ctx.fillStyle = 'rgba(0, 0, 0, 0.7)'
  ctx.fillRect(10, 10, 200, 80) // 调整大小
  
  // 绘制步骤信息
  ctx.fillStyle = '#fff'
  ctx.font = '12px Arial'
  ctx.textAlign = 'left'
  ctx.fillText(`步骤: ${step.step}`, 20, 30)
  ctx.fillText(`时间: ${formatTime(step.timestamp / 1000)}`, 20, 50)
  ctx.fillText(`类型: ${step.type}`, 20, 70)
  
  if (step.data && step.data.playerId) {
    const player = finalRanking.value.find(p => p.id === step.data.playerId)
    ctx.fillText(`玩家: ${player?.name || step.data.playerId}`, 20, 90)
  }
}

// 视频录制功能
const downloadReplay = async () => {
  try {
    // 显示开始提示
    showToastMessage('正在生成视频，请稍候...', 'info')
    
    // 开始录制
    await startReplayRecording()
    
    // 录制完成后下载视频
    downloadVideoFile()
    
  } catch (error) {
    console.error('下载视频失败:', error)
    showToastMessage('下载视频失败，请重试', 'error')
  }
}

// 改进回放录制函数，添加更详细的状态提示
const playReplayWithRecording = async () => {
  try {
    console.log('开始回放录制...')
    
    if (!replayData.value || replayData.value.length === 0) {
      throw new Error('没有回放数据')
    }
    
    // 重置回放状态
    currentReplayStep.value = 0
    replayProgress.value = 0
    
    const totalSteps = replayData.value.length
    
    // 播放回放并录制
    for (let i = 0; i < totalSteps; i++) {
      const step = replayData.value[i]
      
      // 执行回放步骤
      executeReplayStep(step)
      
      // 更新进度
      currentReplayStep.value = i
      replayProgress.value = Math.round((i / (totalSteps - 1)) * 100)
      
      // 每10步显示一次进度
      if (i % 10 === 0 || i === totalSteps - 1) {
        showToastMessage(`正在录制... ${replayProgress.value}%`, 'info')
      }
      
      // 等待一段时间再执行下一步
      await new Promise(resolve => setTimeout(resolve, 200))
    }
    
    console.log('回放录制完成')
    
    // 录制完成后显示最终状态
    showToastMessage('录制完成，正在处理视频文件...', 'info')
    
  } catch (error) {
    console.error('回放失败:', error)
    throw error
  }
}

// 改进下载视频文件函数，添加更好的状态提示
const downloadVideoFile = () => {
  try {
    if (recordedChunks.value.length === 0) {
      throw new Error('没有录制到视频数据')
    }
    
    showToastMessage('正在处理视频文件...', 'info')
    
    const blob = new Blob(recordedChunks.value, { type: 'video/webm' })
    
    if (blob.size === 0) {
      throw new Error('生成的视频文件为空')
    }
    
    // 显示文件大小
    const fileSize = (blob.size / 1024 / 1024).toFixed(2)
    showToastMessage(`视频文件已生成 (${fileSize}MB)，正在下载...`, 'success')
    
    const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
    link.href = url
    link.download = `game-replay-${gameResult.gameId}.webm`
    document.body.appendChild(link)
  link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    showToastMessage('游戏回放视频下载成功！', 'success')
    
  } catch (error) {
    console.error('下载视频失败:', error)
    showToastMessage('下载视频失败，请重试', 'error')
  } finally {
    isRecording.value = false
    recordedChunks.value = []
    recordingProgress.value = 0
  }
}

// 添加缺失的drawReplayCanvas函数
const drawReplayCanvas = () => {
  const canvas = replayCanvas.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  // 设置画布尺寸
  canvas.width = gameReplay.canvasWidth
  canvas.height = gameReplay.canvasHeight
  
  // 清空画布 - 使用游戏页面的背景色
  ctx.fillStyle = '#2c3e50'
  ctx.fillRect(0, 0, gameReplay.canvasWidth, gameReplay.canvasHeight)
  
  // 绘制网格 - 与游戏页面保持一致
  ctx.strokeStyle = 'rgba(255, 255, 255, 0.05)'
  ctx.lineWidth = 1
  
  for (let x = 0; x <= gameReplay.canvasWidth; x += gameReplay.gridSize) {
    ctx.beginPath()
    ctx.moveTo(x, 0)
    ctx.lineTo(x, gameReplay.canvasHeight)
    ctx.stroke()
  }
  
  for (let y = 0; y <= gameReplay.canvasHeight; y += gameReplay.gridSize) {
    ctx.beginPath()
    ctx.moveTo(0, y)
    ctx.lineTo(gameReplay.canvasHeight, y)
    ctx.stroke()
  }
  
  // 绘制出生点安全区域 - 调整位置和大小
  const spawnPoints = [
    { x: 50, y: 50, color: '#ff6b6b' },
    { x: 550, y: 50, color: '#4ecdc4' },
    { x: 550, y: 350, color: '#45b7d1' },
    { x: 50, y: 350, color: '#f7b731' }
  ]
  
  spawnPoints.forEach((spawn, index) => {
    // 绘制出生点安全区域边界
    ctx.strokeStyle = spawn.color
    ctx.lineWidth = 2
    ctx.setLineDash([8, 4])
    ctx.beginPath()
    ctx.arc(spawn.x, spawn.y, 25, 0, Math.PI * 2) // 从50调整为25
    ctx.stroke()
    ctx.setLineDash([])
    
    // 绘制出生点中心标识
    const centerGradient = ctx.createRadialGradient(
      spawn.x, spawn.y, 0,
      spawn.x, spawn.y, 8 // 从12调整为8
    )
    centerGradient.addColorStop(0, '#ffffff')
    centerGradient.addColorStop(0.3, spawn.color + 'FF')
    centerGradient.addColorStop(1, spawn.color + '00')
    
    ctx.fillStyle = centerGradient
    ctx.beginPath()
    ctx.arc(spawn.x, spawn.y, 8, 0, Math.PI * 2) // 从12调整为8
    ctx.fill()
    
    // 中心实心点
    ctx.fillStyle = '#ffffff'
    ctx.strokeStyle = spawn.color
    ctx.lineWidth = 2
    ctx.beginPath()
    ctx.arc(spawn.x, spawn.y, 3, 0, Math.PI * 2) // 从5调整为3
    ctx.fill()
    ctx.stroke()
  })
}

// 生成测试数据函数 - 简化时间逻辑，每秒递增
const generateTestData = () => {
  console.log('生成真实游戏回放测试数据...')
  
  // 确保有玩家数据
  if (finalRanking.value.length === 0) {
    console.log('没有玩家数据，返回空数组')
    return []
  }
  
  const testData = []
  const gameDuration = gameResult.duration || 300 // 5分钟游戏
  
  // 添加初始状态
  testData.push({
    step: 0,
    type: 'init',
    timestamp: 0, // 0秒
    data: {
      players: finalRanking.value.map((player, index) => ({
        id: player.id,
        name: player.name,
        color: player.color,
        spawnPoint: [
          { x: 50, y: 50 },
          { x: 550, y: 50 },
          { x: 550, y: 350 },
          { x: 50, y: 350 }
        ][index] || { x: 300, y: 200 }
      }))
    }
  })
  
  // 模拟游戏过程中的移动和涂色 - 每秒一个步骤
  for (let second = 1; second <= gameDuration; second++) {
    // 为每个玩家生成移动步骤
    finalRanking.value.forEach((player, playerIndex) => {
      const playerId = player.id
      
      // 模拟玩家移动轨迹
      const baseX = [50, 550, 550, 50][playerIndex] || 300
      const baseY = [50, 50, 350, 350][playerIndex] || 200
      
      // 生成移动路径 - 每秒一个移动步骤
      const angle = Math.random() * Math.PI * 2
      const distance = Math.random() * 50 + 25
      const x = Math.max(25, Math.min(gameReplay.canvasWidth - 25, 
        baseX + Math.cos(angle) * distance))
      const y = Math.max(25, Math.min(gameReplay.canvasHeight - 25, 
        baseY + Math.sin(angle) * distance))
      
      testData.push({
        step: testData.length,
        type: 'move',
        timestamp: second * 1000, // 每秒递增：1秒=1000ms, 2秒=2000ms, 3秒=3000ms...
        data: {
          playerId: playerId,
          x: x,
          y: y,
          color: player.color,
          isDrawing: Math.random() > 0.3
        }
      })
      
      // 偶尔圈地完成
      if (Math.random() > 0.8) { // 20%概率圈地
        testData.push({
          step: testData.length,
          type: 'territory',
          timestamp: second * 1000,
          data: {
            playerId: playerId,
            color: player.color,
            area: Math.random() * 20 + 5,
            path: generateRandomPath(baseX, baseY, 50)
          }
        })
      }
      
      // 偶尔死亡和复活
      if (Math.random() > 0.98) { // 2%概率死亡
        testData.push({
          step: testData.length,
          type: 'death',
          timestamp: second * 1000,
          data: {
            playerId: playerId,
            killerId: finalRanking.value[Math.floor(Math.random() * finalRanking.value.length)].id
          }
        })
        
        // 3秒后复活
        testData.push({
          step: testData.length,
          type: 'respawn',
          timestamp: (second + 3) * 1000,
          data: {
            playerId: playerId,
            x: baseX,
            y: baseY
          }
        })
      }
    })
  }
  
  // 添加游戏结束状态
  testData.push({
    step: testData.length,
    type: 'end',
    timestamp: gameDuration * 1000,
    data: {
      winner: finalRanking.value[0]?.id,
      finalRanking: finalRanking.value
    }
  })
  
  console.log('真实游戏回放测试数据生成完成，共', testData.length, '步')
  return testData
}

// 生成随机路径用于圈地
const generateRandomPath = (startX, startY, radius) => {
  const path = []
  const points = Math.floor(Math.random() * 8) + 6 // 6-13个点
  const angleStep = (Math.PI * 2) / points
  
  for (let i = 0; i < points; i++) {
    const angle = i * angleStep + Math.random() * 0.5 - 0.25 // 添加一些随机偏移
    const distance = radius * (0.7 + Math.random() * 0.6) // 70%-130%的半径
    const x = startX + Math.cos(angle) * distance
    const y = startY + Math.sin(angle) * distance
    
    path.push({
      x: Math.max(25, Math.min(gameReplay.canvasWidth - 25, x)), // 从50调整为25
      y: Math.max(25, Math.min(gameReplay.canvasHeight - 25, y)) // 从50调整为25
    })
  }
  
  return path
}

const initializeTestData = () => {
  // 确保有玩家数据
  if (finalRanking.value.length === 0) {
    console.log('没有玩家数据，使用默认数据')
    // 如果没有玩家数据，创建默认数据
    finalRanking.value = [
      {
        id: 'player-1',
        name: '玩家1',
        color: '#ff6b6b',
        area: 25.5,
        totalScore: 1250,
        rankScore: 4
      },
      {
        id: 'player-2',
        name: '玩家2',
        color: '#4ecdc4',
        area: 22.3,
        totalScore: 1100,
        rankScore: -1
      },
      {
        id: 'player-3',
        name: '玩家3',
        color: '#45b7d1',
        area: 28.7,
        totalScore: 1420,
        rankScore: 6
      },
      {
        id: 'player-4',
        name: '玩家4',
        color: '#f7b731',
        area: 23.5,
        totalScore: 1180,
        rankScore: 2
      }
    ]
  }
  
  replayData.value = generateTestData()
  
  console.log('测试数据已初始化:', {
    replaySteps: replayData.value.length,
    gameDuration: gameResult.duration,
    players: finalRanking.value.length
  })
  
  showToastMessage('测试数据已加载，可以开始回放测试！', 'success')
}

const addTestData = () => {
  initializeTestData()
}

const resetTestData = () => {
  replayData.value = []
  currentReplayStep.value = 0
  replayProgress.value = 0
  isReplayPlaying.value = false
  
  // 重置画布
  drawReplayCanvas()
  
  showToastMessage('测试数据已重置', 'info')
}

const showDebugInfo = () => {
  console.log('当前状态:', {
    replayDataLength: replayData.value.length,
    currentStep: currentReplayStep.value,
    isReplayPlaying: isReplayPlaying.value,  // 只使用这一个变量
    isRecording: isRecording.value,
    gameResult: gameResult,
    finalRanking: finalRanking.value
  })
  
  showToastMessage('调试信息已输出到控制台', 'info')
}

// 添加缺失的executeReplayStep函数 - 在playReplayWithRecording之前定义
const executeReplayStep = (step) => {
  if (!step) return
  
  const canvas = replayCanvas.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  console.log('执行回放步骤:', step)
  
  // 根据步骤类型执行不同的操作
  switch (step.type) {
    case 'init':
      drawInitialState(ctx, step.data)
      break
    case 'move':
      drawPaintStep(ctx, step.data) // 修复：move类型应该调用drawPaintStep
      break
    case 'paint':
      drawPaintStep(ctx, step.data)
      break
    case 'territory':
      drawCurrentState(ctx) // 圈地完成后显示当前状态
      break
    case 'death':
      drawCurrentState(ctx) // 死亡后显示当前状态
      break
    case 'respawn':
      drawPaintStep(ctx, step.data) // 复活后显示玩家位置
      break
    case 'end':
      drawCurrentState(ctx) // 游戏结束时显示最终状态
      break
    default:
      drawCurrentState(ctx)
  }
  
  // 绘制当前步骤信息
  drawStepInfo(ctx, step)
}

// 添加缺失的startReplayRecording函数
const startReplayRecording = async () => {
  try {
    console.log('开始录制回放...')
    
    // 检查是否支持MediaRecorder
    if (!window.MediaRecorder) {
      throw new Error('浏览器不支持视频录制功能')
    }
    
    const canvas = replayCanvas.value
    if (!canvas) {
      throw new Error('找不到回放画布')
    }
    
    // 设置录制参数
    const stream = canvas.captureStream(30) // 30fps
    const options = {
      mimeType: 'video/webm;codecs=vp9',
      videoBitsPerSecond: 5000000 // 5Mbps
    }
    
    // 创建MediaRecorder
    mediaRecorder.value = new MediaRecorder(stream, options)
    recordedChunks.value = []
    isRecording.value = true
    recordingProgress.value = 0
    
    // 监听数据可用事件
    mediaRecorder.value.ondataavailable = (event) => {
      if (event.data.size > 0) {
        recordedChunks.value.push(event.data)
      }
    }
    
    // 监听录制完成事件
    mediaRecorder.value.onstop = () => {
      console.log('录制完成，数据块数量:', recordedChunks.value.length)
      isRecording.value = false
      recordingProgress.value = 100
    }
    
    // 监听录制错误事件
    mediaRecorder.value.onerror = (event) => {
      console.error('录制错误:', event.error)
      throw new Error(`录制失败: ${event.error.message}`)
    }
    
    // 开始录制
    mediaRecorder.value.start(1000) // 每秒保存一个数据块
    
    // 播放回放并录制
    await playReplayWithRecording()
    
    // 停止录制
    if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
      mediaRecorder.value.stop()
    }
    
    // 等待录制完成
    await new Promise((resolve) => {
      const checkComplete = () => {
        if (!isRecording.value) {
          resolve()
  } else {
          setTimeout(checkComplete, 100)
        }
      }
      checkComplete()
    })
    
    console.log('录制流程完成')
    
  } catch (error) {
    console.error('录制失败:', error)
    isRecording.value = false
    throw error
  }
}

// 修改进度条处理函数，立即跳转到对应位置
const handleProgressChange = (event) => {
  const newProgress = parseFloat(event.target.value)
  const totalSteps = replayData.value.length - 1
  const targetStep = Math.round((newProgress / 100) * totalSteps)
  
  // 立即跳转到指定步骤
  jumpToStep(targetStep)
  
  // 如果正在播放，暂停播放
  if (isReplayPlaying.value) {
    pauseReplay()
  }
}

// 修改跳转函数，确保立即更新显示
const jumpToStep = (stepIndex) => {
  if (stepIndex < 0 || stepIndex >= replayData.value.length) return
  
  console.log('跳转到步骤:', stepIndex)
  
  // 立即更新当前步骤
  currentReplayStep.value = stepIndex
  const stepData = replayData.value[stepIndex]
  
  if (stepData) {
    // 立即执行步骤，更新画布
    executeReplayStep(stepData)
    
    // 立即更新时间
    if (stepData.timestamp !== undefined) {
      replayTime.value = stepData.timestamp
    }
    
    // 立即更新进度条（避免循环更新）
    const totalSteps = replayData.value.length - 1
    const progress = (stepIndex / totalSteps) * 100
    // 使用 nextTick 确保 DOM 更新后再设置进度条
    nextTick(() => {
      replayProgress.value = Math.round(progress * 10) / 10
    })
    
    console.log('跳转完成 - 步骤:', stepIndex, '时间:', formatTime(replayTime.value / 1000), '进度:', progress + '%')
  }
}

// 修改拖动开始函数
const onProgressDragStart = () => {
  isDragging.value = true
  wasPlaying.value = isReplayPlaying.value
  
  // 立即暂停回放
  if (isReplayPlaying.value) {
    pauseReplay()
  }
  
  console.log('开始拖动进度条')
}

// 修改拖动结束函数
const onProgressDragEnd = () => {
  isDragging.value = false
  
  // 如果之前在播放，继续播放
  if (wasPlaying.value && !isReplayPlaying.value) {
    // 延迟一下再开始播放，确保跳转完成
    setTimeout(() => {
      playReplay()
    }, 100)
  }
  
  console.log('结束拖动进度条')
}

// 添加一个测试函数来验证进度计算
const testProgressCalculation = () => {
  console.log('测试进度计算:')
  console.log('总步骤数:', replayData.value.length - 1)
  console.log('当前步骤:', currentReplayStep.value)
  console.log('当前进度:', replayProgress.value)
  
  // 测试几个关键点的进度
  const testSteps = [0, 100, 1000, 5000, 10000, replayData.value.length - 1]
  testSteps.forEach(step => {
    const progress = (step / (replayData.value.length - 1)) * 100
    console.log(`步骤 ${step}: ${Math.round(progress)}%`)
  })
}

// 添加一个函数来验证时间数据
const validateTimeData = () => {
  console.log('验证时间数据:')
  console.log('总步骤数:', replayData.value.length)
  
  // 检查前几个步骤的时间
  for (let i = 0; i < Math.min(10, replayData.value.length); i++) {
    const step = replayData.value[i]
    console.log(`步骤 ${i}: 时间=${step.timestamp}ms, 类型=${step.type}`)
  }
  
  // 检查最后几个步骤的时间
  const lastSteps = replayData.value.slice(-5)
  lastSteps.forEach((step, index) => {
    const actualIndex = replayData.value.length - 5 + index
    console.log(`步骤 ${actualIndex}: 时间=${step.timestamp}ms, 类型=${step.type}`)
  })
}

// 添加录制状态变量

const recordingStartTime = ref(0)

// 点击游戏画面开始录制
const startRecordingOnClick = () => {
  if (isRecording.value) {
    console.log('已经在录制中')
    return
  }
  
  try {
    const canvas = replayCanvas.value
    if (!canvas) {
      showToastMessage('Canvas未找到', 'error')
      return
    }
    
    console.log('从当前进度开始录制游戏画面...')
    console.log('当前进度:', replayProgress.value + '%', '时间:', formatTime(replayTime.value / 1000))
    
    isRecording.value = true
    recordedChunks.value = []
    recordingStartTime.value = Date.now()  // 记录开始时间
    
    // 配置录制选项
    const stream = canvas.captureStream(15) // 15fps
    const options = {
      mimeType: 'video/webm;codecs=vp8',
      videoBitsPerSecond: 500000
    }
    
    // 检查浏览器支持
    if (!MediaRecorder.isTypeSupported(options.mimeType)) {
      options.mimeType = 'video/webm'
    }
    
    // 创建MediaRecorder
    mediaRecorder.value = new MediaRecorder(stream, options)
    
    // 收集录制数据
    mediaRecorder.value.ondataavailable = (event) => {
      if (event.data.size > 0) {
        recordedChunks.value.push(event.data)
        console.log('录制数据块:', event.data.size, 'bytes')
      }
    }
    
    // 录制结束处理
    mediaRecorder.value.onstop = () => {
      console.log('录制结束，总数据块:', recordedChunks.value.length)
      showToastMessage('录制已停止，可以下载视频', 'success')
    }
    
    // 开始录制
    mediaRecorder.value.start(1000) // 每秒收集一次数据
    showToastMessage(`从 ${formatTime(replayTime.value / 1000)} 开始录制`, 'success')
    
  } catch (error) {
    console.error('开始录制失败:', error)
    isRecording.value = false
    showToastMessage('录制失败: ' + error.message, 'error')
  }
}

// 停止录制
const stopRecording = () => {
  if (!isRecording.value || !mediaRecorder.value) {
    console.log('没有在录制')
    return
  }
  
  try {
    mediaRecorder.value.stop()
    isRecording.value = false
    const duration = Date.now() - recordingStartTime.value
    console.log('录制停止，持续时间:', duration, 'ms')
    showToastMessage('录制已停止', 'info')
  } catch (error) {
    console.error('停止录制失败:', error)
    showToastMessage('停止录制失败', 'error')
  }
}

// 下载录制的视频
const downloadRecording = () => {
  if (recordedChunks.value.length === 0) {
    showToastMessage('没有录制的视频数据', 'error')
    return
  }
  
  try {
    // 创建视频文件
    const blob = new Blob(recordedChunks.value, { type: 'video/webm' })
    const url = URL.createObjectURL(blob)
    
    // 创建下载链接
    const a = document.createElement('a')
    a.href = url
    a.download = `game-recording-${Date.now()}.webm`
    a.style.display = 'none'
    
    // 触发下载
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    
    // 清理URL
    URL.revokeObjectURL(url)
    
    console.log('视频下载完成，文件大小:', blob.size, 'bytes')
    showToastMessage('视频下载完成！', 'success')
    
  } catch (error) {
    console.error('下载失败:', error)
    showToastMessage('下载失败: ' + error.message, 'error')
  }
}

// 清除录制的数据
const clearRecording = () => {
  recordedChunks.value = []
  mediaRecorder.value = null
  recordingStartTime.value = 0  // 重置开始时间
  console.log('录制数据已清除')
  showToastMessage('录制数据已清除', 'info')
}

// 获取录制状态信息
const recordingInfo = computed(() => {
  if (!isRecording.value) {
    return {
      status: '未录制',
      duration: 0,
      size: recordedChunks.value.length
    }
  }
  
  const duration = Date.now() - recordingStartTime.value  // 计算录制时长
  const totalSize = recordedChunks.value.reduce((sum, chunk) => sum + chunk.size, 0)
  
  return {
    status: '录制中',
    duration: Math.floor(duration / 1000),
    size: totalSize
  }
})

// 进度条拖动相关变量
const isDragging = ref(false)
const wasPlaying = ref(false)

// 保存截图功能
const saveScreenshot = async () => {
  try {
    showToastMessage('正在生成截图...', 'info')
    
    // 使用html2canvas库截图
    const html2canvas = await import('html2canvas')
    const canvas = await html2canvas.default(document.querySelector('.result-container'), {
      backgroundColor: '#1e3c72',
      scale: 2,
      useCORS: true,
      allowTaint: true
    })
    
    // 转换为图片并下载
    const link = document.createElement('a')
    link.download = `game-result-${gameResult.gameId}.png`
    link.href = canvas.toDataURL()
    link.click()
    
    showToastMessage('截图保存成功！', 'success')
  } catch (error) {
    console.error('保存截图失败:', error)
    showToastMessage('保存截图失败，请重试', 'error')
  }
}

// 查看个人资料功能
const viewProfile = () => {
  try {
    // 跳转到个人资料页面
    router.push(`/profile/${currentUserId.value}`)
  } catch (error) {
    console.error('跳转个人资料失败:', error)
    showToastMessage('跳转失败，请重试', 'error')
  }
}

// 在游戏进行时记录所有事件
const gameEvents = []

// 记录玩家移动
const recordPlayerMove = (playerId, x, y, timestamp) => {
  gameEvents.push({
    type: 'move',
    playerId,
    x,
    y,
    timestamp,
    isDrawing: true
  })
}

// 记录圈地完成
const recordTerritoryCapture = (playerId, area, path, timestamp) => {
  gameEvents.push({
    type: 'territory',
    playerId,
    area,
    path,
    timestamp
  })
}

// 记录玩家死亡
const recordPlayerDeath = (playerId, killerId, timestamp) => {
  gameEvents.push({
    type: 'death',
    playerId,
    killerId,
    timestamp
  })
}

// 游戏结束时保存回放数据
const saveReplayData = async (gameId, events) => {
  await gameResultAPI.saveGameReplay(gameId, {
    events,
    gameDuration: gameResult.duration,
    players: finalRanking.value
  })
}

// 修改 loadRealReplayData 函数
const loadRealReplayData = () => {
  console.log('尝试加载真实游戏回放数据...')
  
  // 检查是否有全局游戏事件记录器
  if (typeof window !== 'undefined' && window.gameEventRecorder) {
    const realEvents = window.gameEventRecorder.getEvents()
    
    if (realEvents && realEvents.length > 0) {
      console.log('找到真实游戏回放数据:', realEvents.length, '个事件')
      return realEvents
    }
  }
  
  // 检查 localStorage 中是否有保存的回放数据
  try {
    const savedReplayData = localStorage.getItem(`game-replay-${gameResult.gameId}`)
    if (savedReplayData) {
      const parsedData = JSON.parse(savedReplayData)
      if (parsedData && parsedData.length > 0) {
        console.log('从 localStorage 加载回放数据:', parsedData.length, '个事件')
        return parsedData
      }
    }
  } catch (error) {
    console.error('加载 localStorage 回放数据失败:', error)
  }
  
  // 如果没有真实数据，使用模拟数据
  console.log('没有找到真实回放数据，使用模拟数据')
  return generateTestData()
}

// 添加更完善的错误处理
const handleApiError = (error, operation) => {
  console.error(`${operation}失败:`, error)
  
  // 根据错误类型显示不同的提示
  if (error.response?.status === 404) {
    showToastMessage('游戏数据不存在，可能游戏已结束', 'error')
  } else if (error.response?.status === 401) {
    showToastMessage('请先登录后再查看游戏结果', 'error')
  } else if (error.response?.status === 403) {
    showToastMessage('没有权限查看此游戏结果', 'error')
  } else if (error.response?.status >= 500) {
    showToastMessage('服务器错误，请稍后重试', 'error')
  } else {
    showToastMessage(`${operation}失败，请重试`, 'error')
  }
}
</script>

<style scoped>
.game-result-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  padding: 20px;
  position: relative;
  overflow-x: hidden;
}

.background-effects {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
}

.particle {
  position: absolute;
  width: 4px;
  height: 4px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 50%;
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0;
  }
  50% {
    transform: translateY(-100px) rotate(180deg);
    opacity: 1;
  }
}

.result-container {
  position: relative;
  z-index: 1;
  max-width: 1200px;
  margin: 0 auto;
}

.result-header {
  text-align: center;
  margin-bottom: 2rem;
  padding: 2rem;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
}

.result-crown {
  font-size: 4rem;
  margin-bottom: 1rem;
  animation: bounce 2s infinite;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

.result-title {
  color: #fff;
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 1rem;
}

.result-title.winner {
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.result-title.loser {
  color: #ff6b6b;
}

.result-subtitle {
  color: rgba(255, 255, 255, 0.8);
  font-size: 1.1rem;
  margin: 0;
}

.ranking-section {
  margin-bottom: 2rem;
  padding: 1.5rem;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
}

.ranking-section h2 {
  color: #fff;
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
  font-weight: 600;
}

.podium {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 1rem;
  margin-bottom: 2rem;
  height: 240px; /* 从200px增加到240px */
  /* 确保有足够空间 */
  padding: 0 1rem;
}

.podium-position {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  /* 限制每个位置的宽度 */
  max-width: 140px;
  min-width: 120px;
  /* 增加最小高度确保内容完整显示 */
  min-height: 180px; /* 新增最小高度 */
}

.podium-player {
  text-align: center;
  z-index: 2;
  /* 增加容器高度 */
  max-width: 120px;
  min-height: 100px; /* 增加最小高度 */
  overflow: visible; /* 改为visible，让文字完全显示 */
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}

.player-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
  /* 确保头像居中 */
  margin-left: auto;
  margin-right: auto;
  flex-shrink: 0; /* 防止头像被压缩 */
}

.player-name {
  color: #fff;
  font-weight: 600;
  font-size: 0.9rem;
  /* 允许文字换行显示 */
  white-space: normal;
  overflow: visible;
  text-overflow: unset;
  max-width: 100%;
  margin-bottom: 0.25rem;
  /* 确保文字完整显示 */
  line-height: 1.2;
  word-wrap: break-word;
  word-break: break-all;
}

.player-area {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.8rem;
  /* 允许文字换行显示 */
  white-space: normal;
  overflow: visible;
  text-overflow: unset;
  max-width: 100%;
  /* 确保文字完整显示 */
  line-height: 1.2;
  word-wrap: break-word;
}

.podium-base {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  padding: 1rem;
  text-align: center;
  min-width: 80px;
  position: relative;
  /* 增加基础块高度 */
  min-height: 80px; /* 从60px增加到80px */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.position-1 .podium-base {
  height: 140px; /* 从120px增加到140px */
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
}

.position-2 .podium-base {
  height: 110px; /* 从90px增加到110px */
  background: linear-gradient(135deg, #c0c0c0 0%, #e5e5e5 100%);
}

.position-3 .podium-base {
  height: 80px; /* 从60px增加到80px */
  background: linear-gradient(135deg, #cd7f32 0%, #daa520 100%);
}

.position-number {
  color: #fff;
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  /* 确保数字居中 */
  line-height: 1;
  flex-shrink: 0; /* 防止数字被压缩 */
}

.position-score {
  color: rgba(255, 255, 255, 0.9);
  font-size: 0.8rem;
  font-weight: 600;
  /* 允许文字完整显示 */
  white-space: normal;
  overflow: visible;
  text-overflow: unset;
  max-width: 100%;
  line-height: 1.2;
  word-wrap: break-word;
}

.full-ranking {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.rank-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
}

.rank-item.is-current {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.1);
}

.rank-item.is-winner {
  border-color: #ffd700;
  background: rgba(255, 215, 0, 0.1);
}

.rank-item.is-last {
  border-color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
}

.rank-position {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  min-width: 60px;
}

.rank-number {
  color: #fff;
  font-weight: 700;
  font-size: 1.1rem;
}

.rank-medal {
  font-size: 1.2rem;
}

.player-color {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  flex-shrink: 0;
}

.player-info {
  flex: 1;
}

.player-info .player-name {
  color: #fff;
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.player-stats {
  display: flex;
  gap: 1rem;
  font-size: 0.8rem;
}

.area-stat,
.score-stat {
  color: rgba(255, 255, 255, 0.7);
}

.rank-reward {
  text-align: right;
}

.score-change {
  font-weight: 600;
  font-size: 1rem;
}

.score-change.positive {
  color: #4facfe;
}

.score-change.negative {
  color: #ff6b6b;
}

.personal-stats {
  margin-bottom: 2rem;
  padding: 1.5rem;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
}

.personal-stats h2 {
  color: #fff;
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
  font-weight: 600;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.stat-icon {
  font-size: 2rem;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-content {
  flex: 1;
}

.stat-value {
  color: #4facfe;
  font-size: 1.5rem;
  font-weight: 700;
  margin-bottom: 0.25rem;
}

.stat-label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9rem;
}

.replay-section {
  margin-bottom: 2rem;
  padding: 2rem;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.03) 100%);
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.replay-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #667eea, #764ba2, #4facfe, #00f2fe);
  animation: shimmer 3s ease-in-out infinite;
}

@keyframes shimmer {
  0%, 100% { opacity: 0.5; }
  50% { opacity: 1; }
}

.replay-section h2 {
  color: #fff;
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.replay-section h2::before {
  content: '🎬';
  font-size: 1.8rem;
}

.replay-controls {
  margin-top: 1rem;
  display: flex;
  gap: 1.5rem;
  align-items: flex-start;
}

.replay-info {
  display: flex;
  gap: 1.5rem;
  color: rgba(255, 255, 255, 0.9);
  font-size: 0.9rem;
  font-weight: 500;
}

.replay-info span {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.replay-info span::before {
  font-size: 1rem;
}

.replay-info span:first-child::before {
  content: '📊';
}

.replay-info span:last-child::before {
  content: '⏱️';
}

.replay-buttons {
  display: flex;
  gap: 0.75rem;
  justify-content: center;
  padding-top: 0.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.replay-buttons .btn {
  padding: 0.6rem 1.2rem;
  font-size: 0.85rem;
  border-radius: 10px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  min-width: 80px;
}

.replay-buttons .btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.replay-buttons .btn:hover::before {
  left: 100%;
}

.replay-buttons .btn-primary {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(79, 172, 254, 0.3);
}

.replay-buttons .btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(79, 172, 254, 0.4);
}

.replay-buttons .btn-secondary {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
}

.replay-buttons .btn-secondary:hover {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.25) 0%, rgba(255, 255, 255, 0.1) 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

.replay-canvas-container {
  display: flex;
  justify-content: center;
  margin-top: 1.5rem;
  padding: 1rem;
  background: linear-gradient(135deg, rgba(44, 62, 80, 0.8) 0%, rgba(52, 73, 94, 0.8) 100%);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  position: relative;
  overflow: hidden;
}

.replay-canvas-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 20% 20%, rgba(79, 172, 254, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 80%, rgba(102, 126, 234, 0.1) 0%, transparent 50%);
  pointer-events: none;
}

.replay-canvas {
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  background: #2c3e50;
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  position: relative;
  z-index: 1;
}

.replay-canvas:hover {
  border-color: rgba(79, 172, 254, 0.4);
  box-shadow: 
    0 12px 40px rgba(0, 0, 0, 0.4),
    inset 0 1px 0 rgba(255, 255, 255, 0.1),
    0 0 20px rgba(79, 172, 254, 0.2);
}

/* 添加进度条样式 */
.replay-progress {
  width: 100%;
  height: 6px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
  margin-top: 1rem;
  overflow: hidden;
  position: relative;
}

.replay-progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #4facfe, #00f2fe, #667eea);
  border-radius: 3px;
  transition: width 0.3s ease;
  position: relative;
}

.replay-progress-bar::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  animation: progressShimmer 2s ease-in-out infinite;
}

@keyframes progressShimmer {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.button-row {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  color: #fff;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.btn-success {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.btn-danger {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
}

.btn-large {
  padding: 1rem 2rem;
  font-size: 1.1rem;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-icon {
  font-size: 1.1rem;
}

.btn-text {
  white-space: nowrap;
}

.btn-loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .podium {
    gap: 0.5rem;
    padding: 0 0.5rem;
    height: 220px; /* 移动端也增加高度 */
  }
  
  .podium-position {
    max-width: 100px;
    min-width: 80px;
    min-height: 160px; /* 移动端最小高度 */
  }
  
  .podium-player {
    max-width: 100px;
    min-height: 80px; /* 移动端最小高度 */
  }
  
  .player-name {
    font-size: 0.8rem;
  }
  
  .player-area {
    font-size: 0.7rem;
  }
  
  .position-number {
    font-size: 1.5rem;
  }
  
  .position-score {
    font-size: 0.7rem;
  }
  
  .position-1 .podium-base {
    height: 120px; /* 移动端调整高度 */
  }
  
  .position-2 .podium-base {
    height: 100px; /* 移动端调整高度 */
  }
  
  .position-3 .podium-base {
    height: 70px; /* 移动端调整高度 */
  }
}

@media (max-width: 480px) {
  .podium {
    flex-direction: column;
    height: auto;
    gap: 1rem;
    min-height: 300px; /* 确保垂直布局有足够空间 */
  }
  
  .podium-base {
    width: 100%;
    height: 70px !important; /* 统一高度 */
  }
  
  .podium-position {
    max-width: 100%;
    min-width: auto;
    min-height: 120px; /* 垂直布局最小高度 */
  }
  
  .podium-player {
    max-width: 100%;
    min-height: 80px;
  }
}

/* 分享模态框样式 */
.share-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.share-modal-content {
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  border-radius: 16px;
  padding: 0;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.share-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.share-modal-header h3 {
  color: #fff;
  margin: 0;
  font-size: 1.3rem;
  font-weight: 600;
}

.share-close-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  font-size: 1.5rem;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 50%;
  transition: all 0.3s ease;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.share-close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.share-content {
  padding: 2rem;
}

.share-game-info {
  text-align: center;
  margin-bottom: 2rem;
}

.game-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.game-title {
  color: #fff;
  font-size: 1.5rem;
  font-weight: 700;
  margin-bottom: 1rem;
}

.player-performance {
  margin-bottom: 1rem;
}

.performance-text {
  color: #fff;
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.performance-area {
  color: rgba(255, 255, 255, 0.8);
  font-size: 1rem;
}

.challenge-text {
  color: #4facfe;
  font-size: 1rem;
  font-weight: 600;
}

.share-buttons {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.share-btn {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem 1.5rem;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #fff;
  text-decoration: none;
}

.share-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

.wechat-btn {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.weibo-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.link-btn {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.share-icon {
  font-size: 1.5rem;
}

.share-text {
  flex: 1;
  text-align: left;
}

@media (max-width: 768px) {
  .share-modal-content {
    width: 95%;
    margin: 1rem;
  }
  
  .share-content {
    padding: 1.5rem;
  }
  
  .share-buttons {
    gap: 0.75rem;
  }
  
  .share-btn {
    padding: 0.75rem 1rem;
    font-size: 0.9rem;
  }
}

/* Toast提示样式 */
.toast-container {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 2000;
}

.toast {
  display: flex;
    align-items: center;
  gap: 0.5rem;
  padding: 1rem 1.5rem;
  border-radius: 8px;
  color: #fff;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  animation: slideIn 0.3s ease;
}

.toast-success {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.toast-error {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
}

.toast-info {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 录制进度条样式 */
.recording-progress {
  position: fixed;
  top: 0;
  left: 0;
    width: 100%;
  height: 6px;
  background: rgba(255, 255, 255, 0.1);
  z-index: 1000;
  border-radius: 3px;
  overflow: hidden;
}

.recording-progress .progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #4facfe, #00f2fe, #667eea);
  border-radius: 3px;
  transition: width 0.3s ease;
  position: relative;
}

.recording-progress .progress-bar::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  animation: progressShimmer 2s ease-in-out infinite;
}

@keyframes progressShimmer {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.recording-progress .progress-text {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  color: #fff;
  font-size: 0.8rem;
  font-weight: 500;
  z-index: 1;
}

/* 测试状态显示 */
.test-status {
  position: fixed;
  top: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  padding: 10px 15px;
  border-radius: 8px;
  font-size: 0.8rem;
  z-index: 1000;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

@media (max-width: 768px) {
  .test-status {
    top: auto;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
  }
}

/* 优化分享按钮样式 */
.share-buttons {
  display: flex;
    flex-direction: column;
  gap: 0.75rem; /* 减小按钮间距 */
}

.share-btn {
  display: flex;
    align-items: center;
  gap: 0.75rem; /* 减小图标和文字间距 */
  padding: 0.75rem 1.25rem; /* 减小内边距 */
  border: none;
  border-radius: 10px; /* 稍微减小圆角 */
  font-size: 0.9rem; /* 减小字体大小 */
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #fff;
  text-decoration: none;
  min-height: 44px; /* 确保按钮高度合适 */
}

.share-btn:hover {
  transform: translateY(-1px); /* 减小悬停时的移动距离 */
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2); /* 减小阴影 */
}

.wechat-btn {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.weibo-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.link-btn {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.share-icon {
  font-size: 1.2rem; /* 减小图标大小 */
  width: 20px; /* 固定图标宽度 */
  text-align: center;
}

.share-text {
  flex: 1;
  text-align: left;
  font-size: 0.9rem; /* 确保文字大小一致 */
}

/* 优化模态框内容间距 */
.share-content {
  padding: 1.5rem; /* 减小内边距 */
}

.share-game-info {
  text-align: center;
  margin-bottom: 1.5rem; /* 减小底部间距 */
}

.game-icon {
  font-size: 2.5rem; /* 稍微减小图标大小 */
  margin-bottom: 0.75rem;
}

.game-title {
  color: #fff;
  font-size: 1.3rem; /* 减小标题大小 */
  font-weight: 700;
  margin-bottom: 0.75rem;
}

.player-performance {
  margin-bottom: 0.75rem;
}

.performance-text {
  color: #fff;
  font-size: 1rem; /* 减小文字大小 */
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.performance-area {
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.9rem;
}

.challenge-text {
  color: #4facfe;
  font-size: 0.9rem; /* 减小文字大小 */
  font-weight: 600;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .share-modal-content {
    width: 95%;
    margin: 1rem;
  }
  
  .share-content {
    padding: 1.25rem; /* 移动端更小的内边距 */
  }
  
  .share-buttons {
    gap: 0.5rem; /* 移动端更小的间距 */
  }
  
  .share-btn {
    padding: 0.6rem 1rem; /* 移动端更小的内边距 */
    font-size: 0.85rem;
    min-height: 40px;
  }
  
  .share-icon {
    font-size: 1.1rem;
    width: 18px;
  }
  
  .game-icon {
    font-size: 2rem;
  }
  
  .game-title {
    font-size: 1.2rem;
  }
  
  .performance-text {
    font-size: 0.95rem;
  }
}

@media (max-width: 480px) {
  .share-btn {
    padding: 0.5rem 0.75rem;
    font-size: 0.8rem;
    min-height: 36px;
  }
  
  .share-icon {
    font-size: 1rem;
    width: 16px;
  }
  
  .share-text {
    font-size: 0.8rem;
  }
}

/* 录制控制样式 */
.recording-controls {
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.recording-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.9);
}

.status-indicator {
  font-size: 1rem;
  color: #666;
  transition: color 0.3s ease;
}

.status-indicator.recording {
  color: #ff4757;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.recording-buttons {
  display: flex;
  gap: 0.75rem;
  min-width: 200px;
}

.recording-controls {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
}

.recording-controls .btn {
  padding: 0.6rem 0.8rem;
  font-size: 0.8rem;
  border-radius: 10px;
  transition: all 0.3s ease;
  font-weight: 600;
  text-align: center;
  position: relative;
  overflow: hidden;
  flex: 1;
  min-width: 60px;
}

.recording-controls .btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.recording-controls .btn:hover::before {
  left: 100%;
}

.btn-danger {
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(255, 71, 87, 0.4);
}

.btn-danger:hover {
  background: linear-gradient(135deg, #ff3742 0%, #ff2f3a 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 71, 87, 0.6);
}

/* 录制中状态的动画效果 */
.btn-danger:disabled {
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
  animation: recording-pulse 1.5s infinite;
}

@keyframes recording-pulse {
  0%, 100% { 
    opacity: 1;
    box-shadow: 0 4px 15px rgba(255, 71, 87, 0.4);
  }
  50% { 
    opacity: 0.8;
    box-shadow: 0 4px 20px rgba(255, 71, 87, 0.6);
  }
}

.btn-success {
  background: linear-gradient(135deg, #2ed573 0%, #1e90ff 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(46, 213, 115, 0.4);
}

.btn-success:hover {
  background: linear-gradient(135deg, #1e90ff 0%, #2ed573 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(46, 213, 115, 0.6);
}

.btn-icon {
  margin-right: 0.3rem;
  font-size: 0.9rem;
}

.btn-text {
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .replay-buttons {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .replay-buttons .btn {
    width: 100%;
    min-width: auto;
  }
  
  .recording-buttons {
    flex-direction: column;
  }
  
  .recording-buttons .btn {
    width: 100%;
  }
}

/* 可拖动的进度条样式 */
.replay-progress-container {
  margin: 1rem 0;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.progress-info {
  display: flex;
  justify-content: space-between;
    align-items: center;
  margin-bottom: 0.75rem;
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.8);
}

.progress-label {
  font-weight: 600;
  color: #fff;
}

.progress-time {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-weight: 600;
  color: white;
  font-size: 0.85rem;
}

/* 进度条样式 */
.progress-bar-container {
  position: relative;
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  margin: 0.75rem 0;
  cursor: pointer;
  overflow: hidden;
}

.progress-slider {
  position: absolute;
  top: 0;
  left: 0;
    width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
  z-index: 10;
}

.progress-fill {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
  transition: width 0.1s ease;
  pointer-events: none;
  box-shadow: 0 0 8px rgba(102, 126, 234, 0.4);
}

.progress-thumb {
  position: absolute;
  top: 50%;
  width: 16px;
  height: 16px;
  background: #fff;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  pointer-events: none;
  transition: left 0.1s ease;
}

.progress-labels {
  display: flex;
  justify-content: space-between;
  font-size: 0.8rem;
  color: rgba(255, 255, 255, 0.6);
  margin-bottom: 1rem;
}

/* 播放按钮 - 在进度条框内 */
.replay-buttons {
  display: flex;
  gap: 0.75rem;
  justify-content: center;
  padding-top: 0.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.replay-buttons .btn {
  padding: 0.6rem 1.2rem;
  font-size: 0.85rem;
  border-radius: 10px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  min-width: 80px;
}

.replay-buttons .btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.replay-buttons .btn:hover::before {
  left: 100%;
}

.replay-buttons .btn-primary {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(79, 172, 254, 0.3);
}

.replay-buttons .btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(79, 172, 254, 0.4);
}

.replay-buttons .btn-secondary {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
}

.replay-buttons .btn-secondary:hover {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.25) 0%, rgba(255, 255, 255, 0.1) 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

/* 录制控制样式 */
.recording-controls {
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.recording-status {
  display: flex;
    align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.9);
}

.status-indicator {
  font-size: 1rem;
  color: #666;
  transition: color 0.3s ease;
}

.status-indicator.recording {
  color: #ff4757;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.recording-buttons {
  display: flex;
  gap: 0.75rem;
  min-width: 200px;
}

.recording-controls {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  justify-content: center;
    width: 100%;
}

.recording-controls .btn {
  padding: 0.6rem 0.8rem;
  font-size: 0.8rem;
  border-radius: 10px;
  transition: all 0.3s ease;
  font-weight: 600;
  text-align: center;
  position: relative;
  overflow: hidden;
  flex: 1;
  min-width: 60px;
}

.recording-controls .btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.recording-controls .btn:hover::before {
  left: 100%;
}

.btn-danger {
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(255, 71, 87, 0.4);
}

.btn-danger:hover {
  background: linear-gradient(135deg, #ff3742 0%, #ff2f3a 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 71, 87, 0.6);
}

/* 录制中状态的动画效果 */
.btn-danger:disabled {
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
  animation: recording-pulse 1.5s infinite;
}

@keyframes recording-pulse {
  0%, 100% { 
    opacity: 1;
    box-shadow: 0 4px 15px rgba(255, 71, 87, 0.4);
  }
  50% { 
    opacity: 0.8;
    box-shadow: 0 4px 20px rgba(255, 71, 87, 0.6);
  }
}

.btn-success {
  background: linear-gradient(135deg, #2ed573 0%, #1e90ff 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(46, 213, 115, 0.4);
}

.btn-success:hover {
  background: linear-gradient(135deg, #1e90ff 0%, #2ed573 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(46, 213, 115, 0.6);
}

.btn-icon {
  margin-right: 0.3rem;
  font-size: 0.9rem;
}

.btn-text {
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .replay-buttons {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .replay-buttons .btn {
    width: 100%;
    min-width: auto;
  }
  
  .recording-buttons {
    flex-direction: column;
  }
  
  .recording-buttons .btn {
    width: 100%;
  }
}

/* 回放控制区域整体样式 - 水平三栏布局 */
.replay-controls {
  margin-top: 1rem;
  display: flex;
  gap: 1.5rem;
  justify-content: center;
    align-items: center;
  padding: 1.5rem;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(15px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

/* 左侧：播放控制按钮 - 水平排列 */
.playback-buttons {
  display: flex;
  gap: 0.75rem;
  min-width: 200px;
}

.playback-buttons .btn {
  padding: 0.75rem 1rem;
  font-size: 0.9rem;
  border-radius: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  font-weight: 600;
  text-align: center;
  flex: 1;
  min-width: 0;
}

.playback-buttons .btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
    width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.playback-buttons .btn:hover::before {
  left: 100%;
}

.playback-buttons .btn-primary {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(79, 172, 254, 0.4);
}

.playback-buttons .btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(79, 172, 254, 0.6);
}

.playback-buttons .btn-secondary {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
}

.playback-buttons .btn-secondary:hover {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.25) 0%, rgba(255, 255, 255, 0.1) 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

/* 中间：进度条区域 */
.progress-section {
  flex: 1;
  max-width: 600px;
  padding: 0 1rem;
}

.progress-info {
  display: flex;
  justify-content: space-between;
    align-items: center;
  margin-bottom: 1rem;
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.9);
}

.progress-label {
  font-weight: 600;
  color: #fff;
}

.progress-time {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0.3rem 0.8rem;
  border-radius: 20px;
  font-weight: 600;
  color: white;
  font-size: 0.85rem;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

/* 进度条样式 */
.progress-bar-container {
  position: relative;
  height: 10px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 5px;
  margin: 1rem 0;
  cursor: pointer;
  overflow: hidden;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.2);
}

.progress-slider {
  position: absolute;
  top: 0;
  left: 0;
    width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
  z-index: 10;
}

.progress-fill {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border-radius: 5px;
  transition: width 0.2s ease;
  pointer-events: none;
  box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
}

.progress-thumb {
  position: absolute;
  top: 50%;
  width: 18px;
  height: 18px;
  background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(102, 126, 234, 0.3);
  pointer-events: none;
  transition: all 0.2s ease;
  border: 2px solid #fff;
}

.progress-thumb:hover {
  transform: translate(-50%, -50%) scale(1.1);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4), 0 0 0 3px rgba(102, 126, 234, 0.5);
}

.progress-labels {
  display: flex;
  justify-content: space-between;
  font-size: 0.8rem;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 0.5rem;
  font-weight: 500;
}

/* 右侧：录制控制按钮 - 水平排列 */
.recording-buttons {
  display: flex;
    flex-direction: column;
  gap: 0.75rem;
  min-width: 200px;
}

.recording-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.8rem;
  color: rgba(255, 255, 255, 0.9);
  padding: 0.5rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  justify-content: center;
}

.status-indicator {
  font-size: 1rem;
  color: #666;
  transition: color 0.3s ease;
}

.status-indicator.recording {
  color: #ff4757;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.recording-controls {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  justify-content: center;
}

.recording-controls .btn {
  padding: 0.6rem 0.8rem;
  font-size: 0.8rem;
  border-radius: 10px;
  transition: all 0.3s ease;
  font-weight: 600;
  text-align: center;
  position: relative;
  overflow: hidden;
  flex: 1;
  min-width: 60px;
}

.recording-controls .btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.recording-controls .btn:hover::before {
  left: 100%;
}

.btn-danger {
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(255, 71, 87, 0.4);
}

.btn-danger:hover {
  background: linear-gradient(135deg, #ff3742 0%, #ff2f3a 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 71, 87, 0.6);
}

.btn-success {
  background: linear-gradient(135deg, #2ed573 0%, #1e90ff 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(46, 213, 115, 0.4);
}

.btn-success:hover {
  background: linear-gradient(135deg, #1e90ff 0%, #2ed573 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(46, 213, 115, 0.6);
}

.btn-icon {
  margin-right: 0.3rem;
  font-size: 0.9rem;
}

.btn-text {
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .replay-controls {
    flex-direction: column;
    gap: 1rem;
    padding: 1rem;
  }
  
  .playback-buttons,
  .recording-controls {
    width: 100%;
    justify-content: center;
  }
  
  .progress-section {
    width: 100%;
    padding: 0;
  }
  
  .recording-buttons {
    width: 100%;
  }
}
</style>

